const mgRecordTable = require('../models/mgRecordTable');
const inspirecloud = require('@byteinspire/inspirecloud-api');
const ObjectId = inspirecloud.db.ObjectId;
const db = inspirecloud.db;

class mgRecordService {
    /**
     * 列出所有攒钱记录
     */
    async listAll() {
        return await mgRecordTable.where({is_delete: false}).sort({createAt: -1}).find();
    }

    /**
     * 列出分页内攒钱记录
     */
    async queryPage(params) {
        let {page, limit, mg_id} = params;
        let queryParams = {is_delete: false}
        if (mg_id !== undefined && mg_id.trim() !== '') {
            queryParams.mg_id = mg_id;
        }
        //console.log((page - 1) * limit)
        //console.log(limit)
        return await mgRecordTable.where(queryParams)
            .skip((page - 1) * limit)
            .limit(limit)
            .sort({createAt: -1}).find();
    }


    async getOneById(id) {
        return await mgRecordTable.where({_id: ObjectId(id)}).findOne();
    }


    /**
     * 创建一条攒钱记录
     * @param mgRecord 用于创建攒钱记录的数据，原样存进数据库
     * @return {Promise<any>} 返回实际插入数据库的数据，会增加_id，createdAt和updatedAt字段
     */
    async create(mgRecord) {
        return await mgRecordTable.save(mgRecord);
    }

    /**
     * 删除一条攒钱记录
     * @param id 攒钱记录的 _id
     * 若不存在，则抛出 404 错误
     */
    async delete(id) {
        const mgRecord = await mgRecordTable.where({_id: ObjectId(id)}).findOne();
        if (!mgRecord) {
            const error = new Error(`mgRecord:${id} not found`);
            error.status = 404;
            throw error;
        }
        mgRecord.is_delete = true;
        await mgRecordTable.save(mgRecord);
    }


    /**
     * 更新一条攒钱记录
     * @param newmgRecord._id 将会用原对象 merge 此对象进行更新
     * 若不存在，则抛出 404 错误
     */
    async update(newmgRecord) {
        const mgRecord = await mgRecordTable.where({_id: ObjectId(newmgRecord._id)}).findOne();
        if (!mgRecord) {
            const error = new Error(`mgRecord:${newmgRecord._id} not found`);
            error.status = 404;
            throw error;
        }
        Object.assign(mgRecord, newmgRecord);
        mgRecord._id = ObjectId(mgRecord._id)
        await mgRecordTable.save(mgRecord);
    }

    /**
     * 批量删除攒钱计划
     */
    async deleteBatchByIds(ids) {
        for (const id of ids) {
            await this.delete(id);
        }
    }

    async getGroupDescPrice(mgId) {
        let res = await mgRecordTable.where({price: db.gt(0)})
            .where({mg_id: mgId, is_delete: false})
            .groupBy('record_desc')
            .sum('price')
            .as('price_sum')
            .find();
        //统计支出金额
        let spend = await mgRecordTable.where({price: db.lt(0)})
            .where({mg_id: mgId, is_delete: false})
            .groupBy()
            .sum('price')
            .as('price_sum')
            .find();
        //console.log(spend)
        if (spend.length !== 0) {
            res.push({record_desc: '支出', priceSum: -1 * spend[0].price_sum})
        } else {
            res.push({record_desc: '支出', priceSum: 0})
        }
        return res;
    }


    async getGroupDescDay(mgId) {
        //console.log(mgId)
        let res = await mgRecordTable.where({price: db.gt(0)})
            .where({mg_id: mgId})
            .groupBy('record_desc')
            .sum('record_day')
            .as('day_sum')
            .find();
        //console.log(res)
        return res;
    }

}

// 导出 Service 的实例
module.exports = new mgRecordService();
